package com.wx.commons;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wx.core.process.HttpMethod;
import com.wx.core.process.WxApi;
import com.wx.core.vo.request.FansBatchGet;
import com.wx.core.vo.response.Fans;
import com.wx.entity.WxFansUser;
import com.wx.entity.WxTagJson;
import com.wx.service.SysWxuserService;
import com.wx.service.WxFansUserService;
import com.wx.util.FilterSpecialCharacter;
import com.wx.util.HttpUtils;
import com.zyht.bank.entity.WxTags;
import com.zyht.bank.entity.WxTagsExample;
import com.zyht.bank.service.WxTagsService;
import com.zyht.common.util.CommonUtils;
import com.zyht.common.util.Page;

public class SyncTagsFansThread extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(SyncTagsFansThread.class);

    private WxFansUserService wxFansUserService;
    private SysWxuserService sysWxuserService;
    private WxTagsService wxTagsService;
    private String wxid;
    private int uid;
    private String accessToken;
    private int count;//计数,表示更新了多少个数据
    private int total;


    public static String GET_TAG_FANS_LIST = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=%s";

    private List<WxTagJson> tagList;

    private boolean flag = true;
    
    @Override
    public void run() {
    	
    	if (flag) {
    		total = tagList.size();
    	}
    	
        
        // 更新    数据库标签状态为0
		WxTagsExample ex = new WxTagsExample();
		List<WxTags> alltags = wxTagsService.list(ex);
		for (WxTags wxTags : alltags) {
			wxTags.setTagStatus("0");
			wxTagsService.updateById(wxTags);
		}
        
        for (WxTagJson tagInfo : tagList) {
        	String nextOpenId = null;
        	count++;
        	
        	WxTagsExample example = new WxTagsExample();
			example.createCriteria().andTagIdEqualTo(tagInfo.getId());
			List<WxTags> tags = wxTagsService.list(example);
			// 如果已经存在,更新状态和数量
			if(tags.size()>0){
				WxTags wxTags = tags.get(0);
				wxTags.setTagCount(tagInfo.getCount());
				wxTags.setTagName(tagInfo.getName());
				wxTags.setTagStatus("1");
				wxTagsService.updateById(wxTags);
			}else{
				WxTags wxTags = new WxTags();
				wxTags.setTagId(tagInfo.getId());
				wxTags.setTagCount(tagInfo.getCount());
				wxTags.setTagName(tagInfo.getName());
				wxTags.setTagStatus("1");
				wxTagsService.addOne(wxTags);
			}
        	
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("tagid", tagInfo.getId());
            map.put("next_openid", nextOpenId);
            try {

                String resultStr = HttpUtils.postHttpByJsonData(String.format(GET_TAG_FANS_LIST, accessToken), JSON.toJSONString(map));
                logger.error("同步标签下的粉丝:" + resultStr);
                JSONObject json = JSONObject.parseObject(resultStr);

                if (WxResult.isOk(json)) {
                    int fansCount = json.getInteger("count");
                    if (fansCount > 0) {
                        nextOpenId = updateFans(json);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param @param jSONObject    设定文件
     * @return void    返回类型
     * @throws IOException 
     * @throws
     * @author: shanyz
     * @date: 2015年8月3日
     * @Title: UpdateFans
     * @Description: 更新并返回最后一条的openid
     */
    public String updateFans(JSONObject jSONObject) throws IOException {
        String lastOpenid = null;
        JSONArray openids = jSONObject.getJSONObject("data").getJSONArray("openid");
        Page<FansBatchGet> pages = new Page<FansBatchGet>(jSONObject.getIntValue("count"), 1, 100);
        for (int i = 1; i <= pages.getPages(); i++) {
            //生成请求JSON
            pages = new Page<FansBatchGet>(jSONObject.getIntValue("count"), i, 100);
            ArrayList<FansBatchGet> reqList = new ArrayList<FansBatchGet>();
            for (int j = (int) pages.getStart(); j < pages.getEnd(); j++) {
                FansBatchGet fansBatchGet = new FansBatchGet();
                fansBatchGet.setOpenid(openids.getString(j));
                fansBatchGet.setLang("zh_CN");
                reqList.add(fansBatchGet);
            }
            HashMap<String, ArrayList<FansBatchGet>> reqMap = new HashMap<String, ArrayList<FansBatchGet>>();
            reqMap.put("user_list", reqList);
            String requestUrl = WxApi.getRequestUrl(WxApi.GET_BATCH_FANS, accessToken);
           // String requestStr = WxApi.httpsRequestStr(requestUrl, HttpMethod.GET, new Gson().toJson(reqMap));
            String requestStr = WxApi.getRequestUrl(requestUrl, accessToken);
            if (requestStr != null) {
//            	logger.error(requestStr);
                //获取 user_info_list下的数据 gson
                JsonParser jsonParser = new JsonParser();
                JsonElement element = jsonParser.parse(requestStr);
                JsonObject jsonObj = element.getAsJsonObject();
                //fastjson 转换为集合对象
                ArrayList<Fans> list = (ArrayList<Fans>) JSON.parseArray(jsonObj.get("user_info_list").toString(), Fans.class);

                syncFans(list);
                //得到最后一个OPENID
                if (i == pages.getPages())
                    lastOpenid = list.get(list.size() - 1).getOpenid();
            }
        }
        return lastOpenid;
    }

    /**
     * @param @param list    设定文件
     * @return void    返回类型
     * @throws
     * @author: shanyz
     * @date: 2015年8月3日
     * @Title: syncFans
     * @Description: 比较同步粉丝
     */
    public void syncFans(ArrayList<Fans> list) {
        for (Fans fans : list) {
        	try {
        		WxFansUser tempInfo = wxFansUserService.selectByOpenId(fans.getOpenid());
            	if (tempInfo != null ) {
            		// 取消关注的不同步
                    if (fans.getSubscribe() != null && fans.getSubscribe() == 0) {
                    	tempInfo.setSubscribe(0);
                        wxFansUserService.updateByPrimaryKey(tempInfo);
//                        logger.error("更新用户取消关注:" + tempInfo.getNickname());
                    } else {
                    	String[] tagidList = (String[]) fans.getTagid_list();
            			String tags = ",";
            			if (tagidList.length > 0) {
            			    for (int i = 0; i < tagidList.length; i++) {
            			    	tags += tagidList[i] + ",";
            			    }
            			}
            			
            			tempInfo.setHeadimgurl(fans.getHeadimgurl());
                    	tempInfo.setNickname(FilterSpecialCharacter.utf8ToUnicode(fans.getNickname()));
                    	tempInfo.setSex(fans.getSex());
                    	tempInfo.setGroupid(fans.getGroupid());
            			//tempInfo.setTags(tags);
                    	
                    	wxFansUserService.updateByPrimaryKey(tempInfo);
//                    	logger.error("更新用户:" + tempInfo.getNickname());
                    }
            	} else {
            		tempInfo = constructDbFans(fans);
            		wxFansUserService.insert(tempInfo);
//            		logger.error("新插入粉丝用户:" + tempInfo.getNickname());
            	}
        	} catch (Exception e) {
    			logger.error(CommonUtils.getExceptionMessage(e));
    		}
        }
    }

    public HashMap<String, WxFansUser> getDbMap(List<WxFansUser> list) {
        HashMap<String, WxFansUser> map = new HashMap<String, WxFansUser>();
        for (WxFansUser wxFansUser : list) {
            map.put(wxFansUser.getOpenid(), wxFansUser);
        }
        return map;
    }

    public WxFansUser constructDbFans(Fans fans) {
        WxFansUser f = new WxFansUser();
        try {
			BeanUtils.copyProperties(fans, f);
			if (fans.getNickname() != null)
			    f.setNickname(FilterSpecialCharacter.utf8ToUnicode(fans
			            .getNickname()));
			if (fans.getSubscribe_time() != null)
			    f.setSubscribeTime(new Date(fans.getSubscribe_time() * 1000L));
			else
			    f.setSubscribeTime(new Date());
			if (f.getSex() == null)
			    f.setSex(0);
			if (f.getLanguage() == null)
			    f.setLanguage("zh_CN");
			if (f.getGroupid() == null)
			    f.setGroupid(0);
			f.setUid(uid);
			f.setWxid(wxid);
			String[] tagidList = (String[]) fans.getTagid_list();
			if (tagidList.length > 0) {
			    String tags = ",";
			    for (int i = 0; i < tagidList.length; i++) {
			    	tags += tagidList[i] + ",";
			    }
			    //f.setTags(tags);
			}
		} catch (BeansException e) {

			logger.error(CommonUtils.getExceptionMessage(e));
		}
        return f;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public WxFansUserService getWxFansUserService() {
        return wxFansUserService;
    }

    public void setWxFansUserService(WxFansUserService wxFansUserService) {
        this.wxFansUserService = wxFansUserService;
    }

    public SysWxuserService getSysWxuserService() {
        return sysWxuserService;
    }

    public void setSysWxuserService(SysWxuserService sysWxuserService) {
        this.sysWxuserService = sysWxuserService;
    }

    public String getWxid() {
        return wxid;
    }

    public void setWxid(String wxid) {
        this.wxid = wxid;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public static Logger getLogger() {
        return logger;
    }

    public List<WxTagJson> getTagList() {
        return tagList;
    }

    public void setTagList(List<WxTagJson> tagList) {
        this.tagList = tagList;
    }

	public WxTagsService getWxTagsService() {
		return wxTagsService;
	}

	public void setWxTagsService(WxTagsService wxTagsService) {
		this.wxTagsService = wxTagsService;
	}
}
